package com.qf.lja.dao;

import com.qf.lja.enity.Cart;
import com.qf.lja.enity.Product;
import com.qf.lja.util.JDBCUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CartDao {
    public Cart findByProductIdAndUserId(Integer productId, Integer userId) {

        //多表查询
        String sql = "select * from product p join buyr_cart c on p.product_id = c.product_id" +
                " where c.product_id = ? and c.user_id = ?";

        JDBCUtil jdbcUtil = new JDBCUtil();
        ResultSet rs = jdbcUtil.query(sql, productId, userId);

        if (rs == null) {
            System.out.println("sql == null");
            return null;
        }

        try {
            if (rs.next()) {
                return convertToCart(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Cart convertToCart(ResultSet rs) throws SQLException {
        Cart cart = new Cart();
        cart.setShopId(rs.getInt("shop_id"));
        cart.setProductId(rs.getInt("product_id"));
        cart.setUserId(rs.getInt("user_id"));
        cart.setProductQuantity(rs.getInt("product_quantity"));
        cart.setCreatedTime(rs.getDate("created_time"));
        cart.setUpdatedTime(rs.getDate("updated_time"));
        cart.setProduct(convertToProduct(rs));
        return cart;
    }


    public boolean updateCart(Cart cart) {
        String sql = "update buyr_cart set product_quantity = ?, `total_price` = ?" +
                " where shop_id =  ?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        int res = jdbcUtil.update(sql, cart.getProductQuantity(), cart.getTotalPrice(), cart.getShopId());
        return res != -1;
    }

    public boolean updateCart(Integer c_id, double c_price, Integer num) {
        String sql = "update buyr_cart set product_quantity = ?, `total_price` = ?" +
                " where shop_id =  ?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        int res = jdbcUtil.update(sql, num, c_price * (double) num, c_id);
        return res != -1;
    }


    private Product convertToProduct(ResultSet rs) {
        try {
            Product product = new Product();
            product.setProductId(rs.getInt("product_id"));
            product.setProductName(rs.getString("product_name"));
            product.setPrice(rs.getDouble("price"));
            product.setLaunchDate(rs.getString("launch_date")); // Assuming launch_date is stored as String
            product.setImageUrl(rs.getString("image_url"));
            product.setPopularityIndex(rs.getInt("popularity_index"));
            product.setStatus(rs.getInt("status"));
            product.setInventory(rs.getInt("inventory"));
            product.setDescription(rs.getString("description"));
            product.setModifiedAt(rs.getString("modified_at"));
            return product;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Cart> findAllByUserId(Integer userId) {
        //多表查询
        String sql = "select * from product p join buyr_cart c on p.product_id = c.product_id" +
                " where c.user_id = ?";

        JDBCUtil jdbcUtil = new JDBCUtil();
        ResultSet rs = jdbcUtil.query(sql, userId);

        List<Cart> carts = new ArrayList<>();
        try {
            while (rs.next()) {
                carts.add(convertToCart(rs));
            }

            return carts;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return carts;
    }

    public void deleteCart(Integer shopId) {
        String sql = "delete from buyr_cart where shop_id = ?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        jdbcUtil.update(sql, shopId);
        jdbcUtil.closeConnection();
    }

    public boolean addCart(Cart cart) {

        String sql = "insert into buyr_cart(product_id, user_id, product_quantity, `total_price`, created_time, updated_time) " +
                "values(?, ?, ?, ?,CURRENT_TIMESTAMP() ,CURRENT_TIMESTAMP() )";

        JDBCUtil jdbcUtil = new JDBCUtil();
        int res = jdbcUtil.update(sql, cart.getProductId(), cart.getUserId(), cart.getProductQuantity(),
                cart.getProduct().getPrice());
        return res == -1;
    }

    public void clearCart(Integer uid) {
        String sql = "delete from buyr_cart where user_id = ?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        jdbcUtil.update(sql, uid);
        jdbcUtil.closeConnection();
    }

    public Cart getcart(String productId) {
        String sql = "select * from product where product_id = ?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        ResultSet rs = jdbcUtil.query(sql, Integer.parseInt(productId));
        ProductDao productDao = new ProductDao();
        Product product = productDao.findByProductId(Integer.parseInt(productId));
        Cart cart = new Cart();
        cart.setProduct(product);
        if (rs != null) {
            try {
                if (rs.next()) {
                    cart.setProductId(rs.getInt("product_id"));
                    cart.setProductQuantity(1);
                    cart.setCreatedTime(rs.getDate("launch_date"));
                    cart.setUpdatedTime(rs.getDate("launch_date"));
                    cart.setTotalPrice(rs.getDouble("price"));
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return cart;
    }
}


